<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>1_引出生命周期</title>
    <!-- 引入react核心库 -->
    <script src="../React-js/react.development.js"></script>
    <!-- 引入react-dom,用于支持react操作DOM -->
    <script
      type="text/javascript"
      src="../React-js/react-dom.development.js"
    ></script>
    <!-- 引入babel,用于将jsx转换为js -->
    <script type="text/javascript" src="../React-js/babel.min.js"></script>
  </head>
  <body>
    <!-- 
      1.组件从创建到死亡它会经历一些特定的阶段
      2.React组件包含一系列钩子函数(生命周期回调函数) 会在特定的时刻调用
      3.定义组件时，会在特定的生命周期回调函数中，做特定的事

     -->
    <div id="test"></div>
    <script type="text/babel">
      //  constructor() {
      //     super();
      //     setInterval(() => {
      //       let { opacity } = this.state;
      //       opacity = opacity - 0.01;
      //       if (opacity <= 0) opacity = 1;
      //       this.setState({ opacity: opacity });
      //     }, 20);
      //   }
      // 1.创建组件
      class Life extends React.Component {
        state = { opacity: 1 };

        death = () => {
          // 卸载组件
          ReactDOM.unmountComponentAtNode(document.getElementById('test'));
        };

        // 组件挂载完毕时调用
        componentDidMount() {
          this.timer = setInterval(() => {
            let { opacity } = this.state;
            opacity = opacity - 0.01;
            if (opacity <= 0) opacity = 1;
            this.setState({ opacity: opacity });
          }, 20);
        }

        // 组件卸载完毕时调用
        componentWillUnmount() {
          clearInterval(this.timer);
        }

        // render调用的时机：初始化渲染、状态更新之后
        render() {
          return (
            <div>
              <h1 style={{ opacity: this.state.opacity }}>React学不会怎么办</h1>
              <button onClick={this.death}>点击--滚--不活了</button>
            </div>
          );
        }
      }
      // 2.渲染到页面
      ReactDOM.render(<Life />, document.getElementById('test'));
    </script>
  </body>
</html>
